//
//  CreditCore+SwitchController.m
//

#import "CreditCore.h"
#import "NSObject+Tool.h"
#import "LoginViewController.h"
#import "UIViewController+ModalPresentationStyle.h"
#import "HomeViewController.h"
#import "OrderDetailViewController.h"
#import "SelectAccountController.h"



static NSString * const kSkipVersionKey = @"kSkipVersionKey";

@implementation CreditCore (SwitchController)

- (void)loginController:(VoidBlock)finishBlock{
    
    LoginViewController *loginController = [[LoginViewController alloc]init];
    
    UINavigationController *naVController =[[UINavigationController alloc]initWithRootViewController:loginController];
    
    naVController.finishBlock = finishBlock;
    
    naVController.modalPresentationStyle = UIModalPresentationOverFullScreen;
    
    [self.mainTabbarController presentViewController:naVController animated:YES completion:nil];
    
}

- (void)showAlert:(BOOL)isExpire{
    if (self.alertV) {
        [self.alertV removeFromSuperview];
    }
    
    self.alertV = [[TipsAlertTokenLoseView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withTitleStr:@"Login has expired. Please log in again" withSureStr:@"OK"];
    
    UIWindow *window =  [UIApplication sharedApplication].keyWindow;
    if (@available(iOS 14,*)) {
        window =  [[[UIApplication sharedApplication] windows] objectAtIndex:0];
    }
    [window addSubview:self.alertV];
}

-(void)jumpToPage:(NSString *)urlStr{
    if (PMStringIsEmpty(urlStr)) {
        return;
    }
    DLog(@"=======%@",[urlStr getURLParameters]);
    NSDictionary *dic = [urlStr getURLParameters];
    if ([esString(urlStr) containsString:kIsMmlaAppOrderDetail]) {
        OrderDetailViewController *vc = [[OrderDetailViewController alloc] init];
        vc.orderIdStr = esString(dic[@"gardens"]);
        vc.hidesBottomBarWhenPushed = YES;
        [[self currentViewController].navigationController pushViewController:vc animated:YES];
    }
    else if ([esString(urlStr) containsString:kIsMmlaAppHome]){
        [[self currentViewController].navigationController popToRootViewControllerAnimated:NO];
        [self.mainTabbarController setSelectedIndex:0];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Sss" object:nil userInfo:@{@"index":@"1"}];
    }
    else if ([esString(urlStr) containsString:kIsMmlaAppOrder]){
        [[self currentViewController].navigationController popToRootViewControllerAnimated:NO];
        [self.mainTabbarController setSelectedIndex:1];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Sss" object:nil userInfo:@{@"index":@"2"}];
    }
    else if ([esString(urlStr) containsString:kIsMmlaAppLogin]){
        [CreaditUtilsHelper actionWhenLogin:^{
        }];
    }
    else if ([esString(urlStr) containsString:kIsMmlaAppChangeBankCard]){
        SelectAccountController *vc = [[SelectAccountController alloc] init];
        vc.orderIdStr = esString(dic[@"gardens"]);
        vc.orderNoStr = esString(dic[@"growing"]);
        vc.hidesBottomBarWhenPushed = YES;
        [[self currentViewController].navigationController pushViewController:vc animated:YES];
    }
    else {
        
        NSString *fh = @"?";
        if (!PMObjectIsEmpty(dic)) {
            fh = @"&";
        }
        
        urlStr = [urlStr stringByAppendingFormat:@"%@meal=%@&warmed=%@&boyfine=%@&inquiring=%@&kitchen=%@&duty=%@&cheerless=%@&blazed=%@",fh,@"ios",@"mmla",@"common",kAppVersion,esString([[UIDevice currentDevice] name]),esString([UIDevice currentDevice].systemVersion),esString([[UIDevice currentDevice] identifierForVendor].UUIDString),esString([[UIDevice currentDevice] identifierForVendor].UUIDString)];
       
        if (!PMStringIsEmpty(esString([CurrentUser mine].sessionKey))) {
            urlStr = [urlStr stringByAppendingFormat:@"&brightly=%@",esString([CurrentUser mine].sessionKey)];
        }
        
//        urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

        //resolve if url contains '#'
        NSString *realUrlStr = urlStr;
        NSString *lastPathComponent = urlStr.lastPathComponent;
        NSRange queryRange = [lastPathComponent rangeOfString:@"?"];//
        if (queryRange.location != NSNotFound && queryRange.length > 0) {
            
            NSString *queryOrignal = [lastPathComponent substringWithRange:NSMakeRange(queryRange.location+1,lastPathComponent.length -queryRange.location-1)];
               
            NSString *queryEncode = [queryOrignal stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            NSString *lastPathComponentEncode = [lastPathComponent stringByReplacingOccurrencesOfString:queryOrignal withString:queryEncode];
            
            realUrlStr = [urlStr.stringByDeletingLastPathComponent stringByAppendingPathComponent:lastPathComponentEncode];
            
        }
        urlStr = realUrlStr;
       
        
        BaseWebViewController *vc = [[BaseWebViewController alloc] init];
        vc.urlStr = esString(urlStr);
        vc.hidesBottomBarWhenPushed = YES;
        [[self currentViewController].navigationController pushViewController:vc animated:YES];
    }
}

- (void)initLocationJudge{
    
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 100;
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager requestLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    
    CLLocation *newlocation = locations[0];
           
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
   
    [geocoder reverseGeocodeLocation:newlocation completionHandler:^(NSArray * _Nullable placemarks, NSError * _Nullable error) {
    
        if (!error) {
            
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kLatitude];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kLongitude];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kEatStr];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kOfficersStr];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSoldiersStr];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kEarningStr];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStarvedStr];
            
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude] forKey:kLongitude];
            
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude] forKey:kLatitude];
            
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            
            NSString *address = [NSString stringWithFormat:@"%@, %@, %@, %@, %@",placemark.ISOcountryCode,placemark.country,placemark.locality,placemark.subLocality,placemark.thoroughfare];
                               
            DLog(@"---longitude===%f\n---latitude===%f\n====%@",newlocation.coordinate.longitude,newlocation.coordinate.latitude,address);
            
            [[NSUserDefaults standardUserDefaults] setObject:esString(placemark.ISOcountryCode) forKey:kEatStr];
            [[NSUserDefaults standardUserDefaults] setObject:esString(placemark.country) forKey:kOfficersStr];
            [[NSUserDefaults standardUserDefaults] setObject:esString(placemark.locality) forKey:kSoldiersStr];
            [[NSUserDefaults standardUserDefaults] setObject:esString(placemark.subLocality) forKey:kEarningStr];
            [[NSUserDefaults standardUserDefaults] setObject:esString(placemark.thoroughfare) forKey:kStarvedStr];
            
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [self uploadTypeOneDataAgain];
            
        }
        
    }];
    
    [self.locationManager stopUpdatingLocation];
    
    

}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
}

- (void)uploadTypeOneDataAgain{
    NSString *st1 = esString([[NSUserDefaults standardUserDefaults] objectForKey:kRecStartTime]);
    NSString *st2 = esString([[NSUserDefaults standardUserDefaults] objectForKey:kRecEndTime]);
    
    if (!PMStringIsEmpty(st1) && !PMStringIsEmpty(st2)) {
        NSString *idfaStr = [[NSUserDefaults standardUserDefaults] valueForKey:kIDFAStr];
        NSString *longitude = [[NSUserDefaults standardUserDefaults] valueForKey:kLongitude];
        NSString *latitude =  [[NSUserDefaults standardUserDefaults] valueForKey:kLatitude];
        
        NSMutableDictionary *muDic = [NSMutableDictionary dictionaryWithDictionary:@{
            @"quarrel":@"quarrelMianDian",
            @"claimed":@"1",
            @"morpeth":esString([UIDevice currentDevice].identifierForVendor.UUIDString),
            @"smash":PMStringIsEmpty(idfaStr) ? @"":idfaStr,
            @"army":PMStringIsEmpty(latitude) ?  @"": latitude,
            @"sore":PMStringIsEmpty(longitude) ? @"": longitude,
            @"bandaged":esString(st1),
            @"riding":esString(st2),
            @"firmly":@"",
            @"smaller":@"",
        }];
        [BaseDataEngine apiForPath:kUploadMaiDianUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
            if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
                return;
            }
            DLog(@"----upload idfa success again---");
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kRecStartTime];
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:kRecEndTime];
            
        } onCompleteFailur:^(NSError *error) {
            
        } withIsForm:YES];
    }
}
@end



